import React from 'react';
import { message } from 'antd';
import * as uploadJs from 'qiniu-js';
import styles from './style.moudle.scss';
import { ModalPro, Review } from '@/components'
import { getFileType, getToken, uuid } from './utils';
import { LoadingOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons';

type Props = {
  file: File;
  onSuccess(url: string): any;
  onDelete(file: File): any;
}

type State = {
  url: string,
  percent: number;
  loading: boolean;
}

const staticUrl: string = 'http://static.yutao2012.com';

class UploadItem extends React.PureComponent<Props, State> {
  static defaultProps = {
    onSuccess: () => null
  }

  state: State = {
    url: '',
    percent: 0,
    loading: true,
  }

  get observer() {
    return {
      error: this.onError,
      next: this.onProgress,
      complete: this.onComplete
    }
  }

  private subscription: any = null;

  private getFileName = (file: File) => {
    const fileType = getFileType(file.name);
    return `${uuid()}${fileType ? `.${fileType}` : ''}`;
  }

  async componentDidMount() {
    await this.onUpload();
  }

  private onUpload = async () => {
    const { file } = this.props;
    const token: string = await getToken();
    const fileName = this.getFileName(file);
    const observable = uploadJs.upload(file, fileName, token);
    this.subscription = observable.subscribe(this.observer);
  }

  private onError = () => {
    message.error('上传失败，请重新上传！');
  }

  private onProgress = ({ total }: any) => {
    const { percent } = total;
    this.setState({ percent });
  }

  private onComplete = ({ key }: any) => {
    message.success('上传完成！');
    const url:string = `${staticUrl}/${key}`;
    this.props.onSuccess(url);
    this.setState({ loading: false , url });
  }

  componentWillUnmount() {
    this.subscription?.unsubscribe?.();
  }

  render() {
    const {
      url,
      percent,
      loading
    } = this.state;

    const {
      file,
      onDelete
    } = this.props;

    const defaultState = (
      <div className={styles.default_view}>
        <LoadingOutlined/>
        <span className={styles.default_view_text}>
          上传中({percent.toFixed(0)}%)
        </span>
      </div>
    )

    const successState = (
      <div className={styles.upload_review}>
        <img src={url} alt="预览图"/>
        <div className={styles.modal_container}>
          <Review imgUrl={url}>
            <div className={styles.modal_item}>
              <EyeOutlined />
            </div>
          </Review>
          <div
            className={styles.modal_item}
            onClick={() => onDelete(file)}
          >
            <DeleteOutlined />
          </div>
        </div>
      </div>
    );

    return (
      <div className={styles.upload_item}>
        {loading ? defaultState : successState}
      </div>
    )
  }
}

export default UploadItem;
